package com.sanjiahantang.youjiaclient.utils;

import android.util.Log;

import com.sanjiahantang.youjiaclient.config.ConfigValue;

import java.io.File;

/**
 * Created by yan on 2017/12/13.
 * 文件工具类
 */

public class FileUtils {

    private static final String TAG = "FileUtils";

    /**
     * 删除单个文件
     *
     * @param path 要删除的文件全路径
     * @return 文件删除成功则返回true
     */
    public static boolean deleteFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            boolean isDeleted = file.delete();
            Log.w(TAG, file.getName() + "删除结果：" + isDeleted);
            return isDeleted;
        } else {
            Log.w(TAG, "文件删除失败：文件不存在！");
            return false;
        }
    }

    /**
     * 删除文件夹下所有文件
     *
     * @return
     */
    public static void deleteDirectoryAllFile(String directoryPath) {
        final File file = new File(directoryPath);
        deleteDirectoryAllFile(file);
    }

    public static void deleteDirectoryAllFile(File file) {
        if (!file.exists()) {
            return;
        }

        boolean rslt = true;// 保存中间结果
        if (!(rslt = file.delete())) {// 先尝试直接删除
            // 若文件夹非空。枚举、递归删除里面内容
            final File subs[] = file.listFiles();
            final int size = subs.length - 1;
            for (int i = 0; i <= size; i++) {
                if (subs[i].isDirectory())
                    deleteDirectoryAllFile(subs[i]);// 递归删除子文件夹内容
                rslt = subs[i].delete();// 删除子文件夹本身
            }
            // rslt = file.delete();// 删除此文件夹本身
        }

        if (!rslt) {
            L.e("无法删除:" + file.getName());
            return;
        }
    }

    public static String rePath(String path){
        if (path == null){
            return ConfigValue.IMG_IP;
        }

        if (path.length() < "http".length()){
            return ConfigValue.IMG_IP + path;
        }

        if (path.toLowerCase().indexOf("http") != 0){
            path = ConfigValue.IMG_IP + path;
        }

        return path.replaceAll("\\\\", "/");
    }
}
